import { Injectable } from '@angular/core';
import {environment} from '../../environments/environment';
import { Device } from '@ionic-native/device/ngx';
import {HttpClient,HttpHeaders, HttpErrorResponse} from "@angular/common/http";
import { Router,ActivatedRoute,NavigationExtras } from '@angular/router';
import { ToastController } from '@ionic/angular';
import { CustomToastProviderService,CustomToastOption } from '@common-components/common-toast/custom-toast-provider.service';
import { CommonMethodService } from './common.method.service';

interface CommonResponse {
  isSuccess:boolean;
  errorCode:string;
  errorMsg:string;
  responseBody:any;
}


@Injectable({
  providedIn: 'root'
})
export class AuthTokenService {

  constructor(private device:Device,
    private http:HttpClient,
    private router: Router,
    private toastController: ToastController,
    private customToastProviderService:CustomToastProviderService,
    private commonMethodService:CommonMethodService) { }

  getDeviceId(){
    let deviceId = this.device.uuid;
    if(!deviceId){
      deviceId = "TEST_WITH_WEB";
    }
    return deviceId;
  }

  logout(url?:string){
    if(!this.getUserToken() || !this.getAppUserId()){
      this.router.navigate(['/auth/signin-password']);
      return false;
    }
    if(url == '/scm/app/logout.do'){
      localStorage.removeItem(environment.USER_TOKEN);
      this.router.navigate(['/auth/signin-password']);
      return false;
    }
    this.http.post('/scm/app/logout.do',{
      'appUserId':this.getAppUserId()
    }).subscribe((response:CommonResponse) => {
      if(response.isSuccess){
        localStorage.removeItem(environment.USER_TOKEN);
        this.router.navigate(['/auth/signin-password']);
      }
    },(errorResponse)=>{
      this.customToastProviderService.show({
        icon:false,
        iconSuccess:false,
        message:errorResponse.error.errorMsg,
        duration:2000
      });
    });
  }

  disposeErrorForInterceptor(url:string,errorResponse:HttpErrorResponse){
    if(!errorResponse || !errorResponse.error){
      return;
    }
    let errorCode = errorResponse.error.errorCode;
    if(errorCode == 'user_token_expired' || errorCode == 'invalid_token'){
      this.commonMethodService.errorRespCommonToastForInterceptor(errorResponse);
      this.logout(url);
    }else if(errorCode == 'verification_failed'){
      this.commonMethodService.errorRespCommonToastForInterceptor(errorResponse);
      this.logout(url);
    }else if(errorCode == 'device_changed'){
      this.removeAppUserId();
      this.removeUserToken();
      this.removeLoginToken();
      this.commonMethodService.errorRespCommonToastForInterceptor(errorResponse);
      this.logout(url);
    }
  }

  login(response:CommonResponse){
    let userToken = response.responseBody.userToken;
    let loginToken = response.responseBody.loginToken;
    let appUserId = response.responseBody.appUserId;
    if(loginToken){
      this.setLoginToken(loginToken);
    }else{
      localStorage.removeItem(environment.LOGIN_TOKEN);
    }
    
    this.setUserToken(userToken);
    this.setAppUserId(appUserId);
  }

  setAppUserId(appUserId:string){
    localStorage.setItem(environment.APP_USER_ID,appUserId);
  }

  getAppUserId(){
    let appUserId = localStorage.getItem(environment.APP_USER_ID);
    if(!appUserId){
      return "";
    }
    return appUserId;
  }

  removeAppUserId(){
    localStorage.removeItem(environment.APP_USER_ID);
  }

  setLoginToken(loginToken:string){
    localStorage.setItem(environment.LOGIN_TOKEN,loginToken);
  }

  removeLoginToken(){
    localStorage.removeItem(environment.LOGIN_TOKEN);
  }

  getLoginToken():string{
    let loginToken = localStorage.getItem(environment.LOGIN_TOKEN);
    if(!loginToken){
      return "";
    }
    return loginToken;
  }

  setUserToken(userToken:string){
    localStorage.setItem(environment.USER_TOKEN,userToken);
  }

  getUserToken():string{
    let userToken = localStorage.getItem(environment.USER_TOKEN);
    if(!userToken){
      return "";
    }
    return userToken;
  }

  removeUserToken(){
    localStorage.removeItem(environment.USER_TOKEN);
  }
}
